package org.ruanjj.threesumclosest;

import java.util.Arrays;

public class Solution {
    public int threeSumClosest(int[] nums, int target){
        int n = nums.length;
        Arrays.sort(nums);
        int dis = Integer.MAX_VALUE;
        int sum = 0;
        for(int i = 0; i < n;  i++){
            int first = nums[i];
            if(i > 0 && first == nums[i-1]){
                continue;
            }
            for(int j=i+1; j < n; j++){
                int second = nums[j];
                int thirdIndex = n-1;
                if(j >i+1 && second == nums[j-1]){
                    continue;
                }

                while(thirdIndex > j){
                    int currentMinDis = target > first+second+nums[thirdIndex]?target-(first+second+nums[thirdIndex])
                            : (first+second+nums[thirdIndex])-target;
                    if(dis > currentMinDis){
                        dis = currentMinDis;
                        sum = first+second+nums[thirdIndex];
                    }
                    thirdIndex -- ;
                }
            }
        }
        return sum;
    }
}
